package me.moscrop.RootCommand.commands;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.config.Configuration;

public class Kit{
	
	private static List<String> kits;
	private File file;
	private Configuration config;
	private boolean note = false;
	private String pluginDir;
	
	public Kit(String pluginDir)
	{
		this.pluginDir = pluginDir;
		file = new File(pluginDir + File.separator + "kits.yml");
			
		config = new Configuration(file);
        config.load();

        new File(pluginDir).mkdir();

        if(!file.exists()){
            try {
                file.createNewFile();
                addDefaultItems();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
     
	}
	
	private void addDefaultItems() {
		
		try {
			FileWriter fstream;
			fstream = new FileWriter(pluginDir + File.separator + "kits.yml");
			BufferedWriter out = new BufferedWriter(fstream);
	  out.write("#Kit name is case sensitive!" +
	  			"#KitName:\n" +
		  		"   #itemID: quantity\n" +
		  		"   #itemID:damage quantity\n" +
		  		"wool:" +
		  		"   '35': 64" +
		  		"   '35:1': 64" +
		  		"   '35:2': 64" +
		  		"   '35:3': 64" +
		  		"   '35:4': 64" +
		  		"   '35:5': 64" +
		  		"   '35:6': 64" +
		  		"   '35:7': 64" +
		  		"   '35:8': 64" +
		  		"   '35:9': 64" +
		  		"   '35:10': 64" +
  	  			"   '35:11': 64" +
  	  			"   '35:12': 64" +
  	  			"   '35:13': 64" +
  	  			"   '35:14': 64" +
  	  			"   '35:15': 64" +
  	  			"tools:" +
  	  			"   '277': 1" +
  	  			"   '278': 1" +
  	  			"   '279': 1");
		  out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public void loadConfig()
	{

		config.load();

		Logger log = Logger.getLogger("Minecraft");
		kits = config.getKeys();
		char[] only = {'0','1','2','3','4','5','6','7','8','9',':'};
		boolean result;
		note = false;
		for(String kit : kits)
		{
			List<String> selectedItems = config.getKeys(kit);
			
			for(int i = 0; i < selectedItems.size(); i ++)
			{
				String currentItem = selectedItems.get(i);
				for(char current : currentItem.toCharArray())
				{
					result = false;
					for(char currentTest : only)
					{
						if( currentTest == current)
						{
							result = true;
							
						}
					}
					if(result == false)
					{
						config.removeProperty(kit + "." + currentItem);
						log.info(ChatColor.RED + "Warning, item " + currentItem + " in kit " + kit + " contains invalid character");
						note = true;
					}
				}
			}
		}
	
	}
	
	public void loadConfig(CommandSender sender)
	{
		config.load();
		Logger log = Logger.getLogger("Minecraft");
		kits = config.getKeys();
		char[] only = {'0','1','2','3','4','5','6','7','8','9',':'};
		boolean result;
		note = false;
		for(String kit : kits)
		{
			List<String> selectedItems = config.getKeys(kit);
			
			for(int i = 0; i < selectedItems.size(); i ++)
			{
				String currentItem = selectedItems.get(i);
				
				for(char current : currentItem.toCharArray())
				{
					result = false;
					for(char currentTest : only)
					{
						if( currentTest == current)
						{
							result = true;
							
						}
					}
					if(result == false)
					{
						config.removeProperty(kit + "." + currentItem);
						log.info(ChatColor.RED + "Warning, item " + currentItem + " in kit " + kit + " contains invalid character");
						sender.sendMessage(ChatColor.RED + "Warning, item " + currentItem + " in kit " + kit + " contains invalid character");
						note = true;
						break;
					}
				}
			}
		}
		sender.sendMessage(ChatColor.GREEN + "Kits reloaded");
	
	}
	
	public boolean onCommand(CommandSender sender, String[] args)
	{
		
		if(note == true)
		{
			sender.sendMessage(ChatColor.RED + "Warning, there are error's in the kit.yml");
			sender.sendMessage(ChatColor.RED + "Please run /kit reload for more details.");
		}
		
		//give instructions
		if(args.length == 0 || (args.length == 1 && (args[0].contentEquals(""))))
		{
			displayHelp(sender);
			return true;
		}
		
		if(args[0].contentEquals("list"))
		{
			listKits(sender);
			return true;
		}
		
		if(args[0].contentEquals("reload"))
		{
			loadConfig(sender);
			return true;
		}
		
		if(args[0].contentEquals("content"))
		{
			displayContent(sender,args[1]);
			return true;
		}
		
		if(kits.indexOf(args[0]) != -1)
		{
			giveKit(sender, args[0]);
			return true;
		}
		
		sender.sendMessage(ChatColor.RED + "Error: arguemnt '" + args[0] + "' is not a kit or a command.");
		displayHelp(sender);
		
		return true;
	}
	
	private void displayContent(CommandSender sender, String kit)
	{
		List<String> selectedKit = config.getKeys(kit);
		String itemName;
		
		if(selectedKit.size() == 0)
		{
			sender.sendMessage(ChatColor.RED + "Error: Kit " + kit + " does not exists." );
		}
		
		sender.sendMessage(ChatColor.RED + "Content's of kit " + kit);
		sender.sendMessage(ChatColor.RED + "-----------------------");
		sender.sendMessage(ChatColor.RED + "Item:Damage - Quantity");
		for(int i = 0; i < selectedKit.size(); i ++)
		{
			itemName = selectedKit.get(i);
			sender.sendMessage(ChatColor.RED + itemName + " - " + config.getProperty(kit+ "." + itemName));
		}
		
	}
	
	private static void displayHelp(CommandSender sender)
	{
		sender.sendMessage(ChatColor.RED + "Usage: /kit list");
		sender.sendMessage(ChatColor.RED + "Usage: /kit reload");
		sender.sendMessage(ChatColor.RED + "Usage: /kit content <kit name>");
		sender.sendMessage(ChatColor.RED + "Usage: /kit <kit name>");
	}
	
	private static void listKits(CommandSender sender)
	{
		sender.sendMessage(ChatColor.RED + "Avaible kits");
		sender.sendMessage(ChatColor.RED + "-------------");
		for(String kitName : kits)
		{
			sender.sendMessage(ChatColor.RED + kitName);
		}
	}
	
	public void giveKit(CommandSender sender, String kit)
	{
		
		if((sender instanceof Player) == false)
		{
			sender.sendMessage("This isnt a command for the console silly.");
			return;
		}
		
		List<String> selectedKit = config.getKeys(kit);
		String itemName;
		int collonPosition;
		ItemStack item = new ItemStack(0);
		Inventory inv = ((Player) sender).getInventory();
		
		for(int i = 0; i < selectedKit.size(); i ++)
		{
			itemName = selectedKit.get(i);
			collonPosition = itemName.indexOf(':');
			//Does item name have damage value
			if(collonPosition == -1)
			{
				
				item.setTypeId(toInt(itemName));
				item.setDurability((short) 0);
				item.setAmount(toInt(config.getProperty(kit + "." + itemName)));
				inv.addItem(item);
			
			//ensure there aren't two :
			}else if(itemName.lastIndexOf(":") == collonPosition){
	
				item.setTypeId(toInt(itemName.substring(0, collonPosition)));
				item.setDurability(toShort(itemName.substring(collonPosition + 1)));
				item.setAmount(toInt(config.getProperty(kit + "." + itemName.substring(0, collonPosition))));
				inv.addItem(item);
			}
		}
		
		
		sender.sendMessage(ChatColor.GREEN + "You was given the " + kit + " kit");
	}
	
	public int toInt(Object prop)
	{
		if(prop instanceof String)
		{
			return Integer.parseInt((String) prop);
		}else{
			return (Integer) prop;
		}
	}
	
	public short toShort(Object prop)
	{
		if(prop instanceof String)
		{
			return Short.parseShort((String) prop);
		}else{
			
			return (Short) prop;
		}
	}
	
}
